<template>
  <div>
    <div style="overflow: hidden">

      <el-select
        style="float: left;width: 300px;padding: 5px"
        v-model="optionsOwnerUserId"
        multiple
        filterable
        remote
        reserve-keyword
        placeholder="负责人"
        :remote-method="getOwnerUserInfo"
        :loading="loading">
        <el-option
          v-for="(item,index) in owner_user_info"
          :key="index"
          :label="item.username"
          :value="item.id">
        </el-option>
      </el-select>

      <!--自动化数据-->
      <el-select
        style="float: left;width: 300px;padding: 5px"
        v-model="optionsAutomatedTaskId"
        multiple
        filterable
        remote
        reserve-keyword
        placeholder="请输入自动化标题"
        :remote-method="get_automated_task_info"
        :loading="loading">
        <el-option
          v-for="(item,index) in automated_task_info"
          :key="index"
          :label="item.title"
          :value="item.id">
        </el-option>
      </el-select>

      <el-select style="float: left;padding: 5px" v-model="status" placeholder="请选择类型">
        <el-option
          v-for="(item,index) in optionsAutomated"
          :key="index"
          :label="item.value"
          :value="item.id">
        </el-option>
      </el-select>

      <div class="block" style="float: left;padding: 5px;">
        <el-date-picker
          disabled
          v-model="startEndTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </div>

      <div class="block" style="float: left;padding: 5px;">
        <span class="demonstration">月</span>
        <el-date-picker
          v-model="monthTime"
          type="month"
          placeholder="选择月">
        </el-date-picker>
      </div>

      <div style="float: left;padding: 5px">
        <el-button type="primary" plain @click="createReport()">生成报告</el-button>
      </div>
    </div>

    <baseEcharts :id="'month1'" v-if="is_show" :data="option5" style="height:700px;"></baseEcharts>

  </div>
</template>

<script>
  import baseEcharts from './baseEcharts.vue'

  export default {
    // name: "reportWeeks",
    data() {
      return {
        status: 2,
        // choices设置
        optionsAutomated: [],  // 存储CommonChoices实际数据的列表
        is_show: false,

        startEndTime: [],  // 开始结束时间
        monthTime: '',  // 月

        id: 'myReportWeeks',
        ChartLineGraph: null,

        // 编辑和添加选中的数据id
        loading: false,
        optionsAutomatedTaskId: [],
        optionsOwnerUserId: [],

        owner_user_info: [],  // 记录所有者
        automated_task_info: [],  // 自动化明细

        // 数据设置
        ListDataURL: this.$http.TestReportURL,  // 表格列表数据获取
        tableData: [],  // 阿贾克斯获取的初始数据

        month_day_list: [],  // 月的日期列表

        option5: {
          legend: {},
          tooltip: {
            trigger: 'axis',
            showContent: false
          },
          toolbox: {
            show: true,
            feature: {
              dataZoom: {
                yAxisIndex: 'none'
              },
              dataView: {readOnly: false},
              magicType: {type: ['line', 'bar']},
              restore: {},
              saveAsImage: {}
            }
          },
          dataset: {},
          xAxis: {
            type: 'category',
            // data: ["2012", "2013", "2014", "2015", "2016", "2017"]
          },
          yAxis: {gridIndex: 0},
          grid: {top: '55%'},
          series: []
        },

      }
    },
    created() {
      // 发送啊假克丝请求
      this.optionsAutomated = this.getChoices.automated;
      this.setOptions();
      this.get_day_list();
      this.optionsOwnerUserId[0] = this.getUserInfo.id;
      this.getOwnerUserInfo(this.getUserInfo.username);
      this.createReport();
    },
    methods: {
      setOptions() {
        let options = [this.optionsAutomated];
        options.forEach(lis => {
          lis.unshift({'id': null, 'value': '请选择状态'})
        })
      },

      createReport() {
        this.is_show = false;
        let queryData = {
          'owner_user': this.optionsOwnerUserId[0],
          'create_time__gte': this.startEndTime[0], // 大于等于
          'create_time__lte': this.startEndTime[1],   // 小于
          'automated_task': this.optionsAutomatedTaskId.length ? this.optionsAutomatedTaskId[0] : null,
          'status': this.status,
          'report_status': 'report_weeks',
        };
        console.log(queryData);
        let newQueryData = {};
        for (let key in queryData) {
          if (queryData[key]) {
            newQueryData[key] = queryData[key];
          }
        }
        this.$http.getApiFunc(this.$http.addApiStatus)(this.ListDataURL, newQueryData)
          .then(res => {
            this.$alert(res.data.msg, '提示', {
              confirmButtonText: '确定'
            });
            if (res.data.status) {
              this.tableData = []
            } else {
              this.tableData = res.data.data;
              this.is_show = true;
            }
          })
          .catch(err => {
            console.log(err);
          })
      },

      //  按项目名称搜索的函数
      inputFunc() {
        this.$myTool.inputFunc(this)
      },

      getOwnerUserInfo(query) {
        this.$myTool.getObjList(this, this.$http.accountURL, this.owner_user_info, query)
      },

      // 自动化数据获取
      get_automated_task_info(query) {
        this.$myTool.getObjList(this, this.$http.AutomatedTaskURL, this.automated_task_info, query)
      },

      // 获取日期列表
      get_day_list() {
        let value = new Date();
        value.setDate(1);

        let strValue = this.$echarts.format.formatTime('yyyy-MM-dd', value);
        this.startEndTime[0] = strValue;
        let endDate = this.$echarts.number.parseDate(strValue);
        endDate.setMonth(endDate.getMonth() + 1);
        this.startEndTime[1] = this.$echarts.format.formatTime('yyyy-MM-dd', endDate);
        let startDate = this.$echarts.number.parseDate(this.startEndTime[0]);
        while (startDate < endDate) {
          this.month_day_list.push(this.$echarts.format.formatTime('yyyy-MM-dd', startDate));
          startDate.setDate(startDate.getDate() + 1);
        }
        // this.monthTime = startDate;
      },

      get_option5() {
        let option = this.option5;
        let xNameList = ['用例总数', '步骤总数', '执行用例数', '执行步骤数', '用例失败数', '步骤失败数', '用例未执行数', '步骤未执行数'];
        let field_all_list = ['cases_sum', 'cases_detail_sum', 'cases_execute_sum', 'cases_detail_execute_sum', 'cases_failure_sum', 'cases_detail_failure_sum', 'cases_not_execute_sum', 'cases_detail_not_execute_sum'];
        option.title = {text: '按月测试报告'};
        option.series = [];
        option.dataset.source = [['product'],];
        for (let k = 0; k < xNameList.length; k++) {
          option.dataset.source[k + 1] = [xNameList[k]];
          option.series.push({type: 'line', smooth: true, seriesLayoutBy: 'row'})
        }
        option.series.push({
          type: 'pie',
          id: 'pie',
          radius: '30%',
          center: ['50%', '25%'],
          label: {
            formatter: '{b}: {@2012} ({d}%)'
          },
          encode: {
            itemName: 'product',
            // value: '2020-01-01',
            // tooltip: '2020-01-01'
          }
        });
        for (let j = 0; j < this.month_day_list.length; j++) {
          option.dataset.source[0][j + 1] = this.month_day_list[j];
          let item = this.tableData[this.month_day_list[j]];
          for (let i = 0; i < field_all_list.length; i++) {
            if (item) {
              option.dataset.source[i + 1].push(item[field_all_list[i]]);
            } else {
              option.dataset.source[i + 1].push(0);
            }
          }
        }
      }
    },

    components: {
      baseEcharts
    },

    watch: {
      optionsAutomatedTaskId: function (value) {
        value = this.$myTool.delLenghtList(1, value, this);
      },

      optionsOwnerUserId: function (value) {
        value = this.$myTool.delLenghtList(1, value, this);
      },

      tableData: function (value) {
        this.is_show = false;
        if (Object.keys(value).length > 0) {
          this.get_option5();
          this.is_show = true;
        }
      },

      monthTime: function (value) {
        this.startEndTime = [];
        this.month_day_list = [];
        if (value) {
          console.log(this.monthTime);
          let strValue = this.$echarts.format.formatTime('yyyy-MM-dd', value);
          this.startEndTime[0] = strValue;
          let endDate = this.$echarts.number.parseDate(strValue);
          endDate.setMonth(endDate.getMonth() + 1);
          this.startEndTime[1] = this.$echarts.format.formatTime('yyyy-MM-dd', endDate);
          let startDate = this.$echarts.number.parseDate(this.startEndTime[0]);
          while (startDate < endDate) {
            this.month_day_list.push(this.$echarts.format.formatTime('yyyy-MM-dd', startDate));
            startDate.setDate(startDate.getDate() + 1);
          }
        }
      }
    },
    computed: {
      getChoices() {
        return this.$store.state.choicesInfo
      },
      getUserInfo() {
        return this.$store.state.userInfo
      }
    },
  }
</script>

<style scoped>
  .paging {
    padding-top: 20px;
  }

  .input-data {
    float: left;
    width: 200px;
    padding: 5px 5px;
  }

  .mytable {
    /*width: 120px;*/
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
</style>
